var ocrCtr = {};
(function(ctx,$){
    //全局变量
    var $ocr_field_container = $("#ocr_field_container");
    var props = {};
    var subProps = {};
    var formField = {};

    //入口函数
    ctx.init = function(params){
    	//参数
    	initParams(params);
    	//事件绑定
    	initPageEvent();
    	
    	//加载数据
    	$ocr_field_container.empty();
        if(params.params && params.params.subPropMapping){
        	$.each(params.params.subPropMapping,function(i,v){
        		initSubPropRow(v.source);
            	initFormFieldRow(v.target);
        	});
        } else {
        	initSubPropRow();
        	initFormFieldRow();
        	
        }
    }

    /**
     * 有初始化数据的时候加载ocr属性
     * @param ocrType
     * @param subProp
     * @param formField
     */
    var initSubPropRow = function(subPropMapping){
        var $newProp = $($("#tpl-ocrProp").html());
        var $newProp_leftField = $newProp.find("select.leftField");
        $ocr_field_container.append($newProp);
        if(subProps.length){
        	var options = "";
        	$.each(subProps,function (i,v) {
        		options += '<option value="' + v.key + '"'+(subPropMapping == v.key ? ' selected ':'') +'>' + v.name + '</option>';
        	});
        	$newProp_leftField.append(options);
        	return ;
        }
        $.ajax({
            url : "/seeyon/rest/cap4/ocrCustom/fieldProperty",
            success : function(data){
                var names = data.data;
                var options = "";
                $.each(names,function (i,v) {
                    subProps[v.key] = v;
                    options += '<option value="' + v.key + '"'+(subPropMapping == v.key ? ' selected ':'') +'>' + v.name + '</option>';
                });
                $newProp_leftField.append(options);
            },
            error : function(e){
            }
        });
    }

    /**
     * 有初始化数据的时候加载表单字段
     * @param ocrType
     * @param subProp
     * @param selectedFormField
     * @param $dom
     */
    var initFormFieldRow = function(subPropMapping){
    	var $dom = $ocr_field_container.find("select.rightField");
    	if(formField.length){
        	var options = "";
        	$.each(formField,function (i,v) {
        		options += '<option value="' + v.name + '"'+(subPropMapping == v.name ? ' selected ':'')+'>' + v.display + '</option>';
        	});
        	$dom.append(options);
        	return ;
        }
        $.ajax({
            url : "/seeyon/rest/cap4/ocrCustom/formFields?formId=" + ctx.formId + "&currentField=" + ctx.currentField,
            success : function(data){
                var formFieldData = data.data;
                var options = '';
                $.each(formFieldData,function(i,v){
                    formField[v.name] = v;
                    options += '<option value="' + v.name + '"'+(subPropMapping == v.name ? ' selected ':'')+'>' + v.display + '</option>';
                });
                $dom.append(options);
            },
            error : function(e){
            }
        });
    }

    var initParams = function(params){
        ctx.formId = params.formBaseInfo.formBaseInfo.formInfo.id;
        ctx.currentField = params.currentfield.name;
        ctx.initData = params.params;
    }
    
    var initPageEvent = function(){
        //加号事件
        $ocr_field_container.on('click','.cap-icon-zengjia',function(){
            var $newProp = $($("#tpl-ocrProp").html());
            $newProp.find("select.leftField").html($(".ocr-props-row .leftField:first").html());
            $newProp.find("select.rightField").html($(".ocr-props-row .rightField:first").html());
            $newProp.find("option:selected").each(function(){
            	$(this).prop("selected", false);
            });
            $(this).parent().after($newProp);
        });
        //减号事件
        $ocr_field_container.on('click','.cap-icon-jianshao',function(){
            if($ocr_field_container.find(".ocr-props-row").length > 1){
                $(this).parent().remove();
            }else{
                top.$.alert($.i18n("com.cap.ctrl.ocr.set.cannotdel"));
            }
        });
    }

    var validate = function(){
        var validated = true;
        $ocr_field_container.find('.ocr-props-row .error-title').removeClass('active');
        $ocr_field_container.find('.ocr-props-row .error-title').prop('title','');
        $ocr_field_container.find('.ocr-props-row .div_sel3').removeClass('active');
        //左边判断重复
        var rows = $ocr_field_container.find(".ocr-props-row");
        var hash = {};
        for(var i = 0;i < rows.length;i++){
            var $left = $(rows[i]).find('.leftField');
            var $right = $(rows[i]).find('.rightField');
            var $error = $(rows[i]).find('.error-title');
            var errorMsg = '';
            if(!$left.val() && $right.val()){
                $left.addClass('active');
                $error.addClass('active');
                errorMsg = $.i18n('com.cap.ctrl.ocr.set.paramnull');
                validated = false;
            }
            if($left.val() && !$right.val()){
                $right.addClass('active');
                $error.addClass('active');
                if(!errorMsg){
                    errorMsg = $.i18n('com.cap.ctrl.ocr.set.fieldnull');
                }else{
                    errorMsg += '，'+$.i18n('com.cap.ctrl.ocr.set.fieldnull');;
                }
                validated = false;
            }
            if($right.val()){
                if(hash[$right.val()]){
                    $right.addClass('active');
                    $error.addClass('active');
                    if(!errorMsg){
                        errorMsg = $.i18n('com.cap.ctrl.ocr.set.repeatfield');
                    }else{
                        errorMsg += '，'+$.i18n('com.cap.ctrl.ocr.set.repeatfield');
                    }
                    validated = false;
                }
                hash[$right.val()] = true;
            }
            $error.prop('title',errorMsg);
        }
        return validated;
    };

    /**
     * 判断当前是否设置了属性
     */
    var hasSelectProp = function(){
        var $ocrPropRows = $ocr_field_container.find(".ocr-props-row");
        if($ocrPropRows.length > 1)
            return true;
        if($($ocrPropRows[0]).find(".leftField").val() || $($ocrPropRows[0]).find(".rightField").val())
            return true;

        return false;
    };

        ctx.submit = function(){
        //校验选择的映射双方字段
        if(!validate())
            return{valid:false};

        var mapping = {};
        var subPropMapping = [];
        var $ocrPropRows = $ocr_field_container.find(".ocr-props-row");
        var isEmpty = true;
        for(var i = 0; i < $ocrPropRows.length;i++){
            var $item = $($ocrPropRows[i]);
            if($item.find(".leftField").val() != ""){
                var obj = {
                    source : $item.find(".leftField").val(),
                    target : $item.find(".rightField").val()
                }
                subPropMapping.push(obj);
                isEmpty = false;
            }
        }
        if(isEmpty){
            subPropMapping.push({
                source : "",
                target : ""
            });
        }
        mapping.subPropMapping = subPropMapping;
            return {valid:true,data:mapping};
    }

})(ocrCtr,typeof $ === 'undefined' ? top.$ : $);
